/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pigx.wallet.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import com.pig4cloud.pigx.user.entity.User;
import com.pig4cloud.pigx.wallet.api.feign.RemoteRippleUserService;
import com.pig4cloud.pigx.wallet.bo.WalletStatisticsBO;
import com.pig4cloud.pigx.wallet.constant.WalletStatusEnum;
import com.pig4cloud.pigx.wallet.dto.MobileRechargeRecord;
import com.pig4cloud.pigx.wallet.entity.RechargeRecord;
import com.pig4cloud.pigx.wallet.service.RechargeRecordService;
import org.springframework.security.access.prepost.PreAuthorize;
import com.pig4cloud.pigx.common.excel.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 充值记录
 *
 * @author
 * @date 2022-08-12 18:31:59
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/rechargerecord")
@Api(value = "rechargerecord", tags = "充值记录管理")
public class RechargeRecordController {

	private final RechargeRecordService rechargeRecordService;

	private final RemoteRippleUserService remoteRippleUserService;

	/**
	 * 分页查询
	 *
	 * @param page           分页对象
	 * @param rechargeRecord 充值记录
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('wallet_rechargerecord_view')")
	public R<WalletStatisticsBO<RechargeRecord>> getRechargeRecordPage(Page<RechargeRecord> page, RechargeRecord rechargeRecord) {
		QueryWrapper<RechargeRecord> wrapper = new QueryWrapper<RechargeRecord>() {{
			if (rechargeRecord.getUserId() != null) {
				eq("user_id", rechargeRecord.getUserId());
			}
			if (StrUtil.isNotBlank(rechargeRecord.getCurrency())) {
				eq("currency", rechargeRecord.getCurrency());
			}
			if (StrUtil.isNotBlank(rechargeRecord.getPublicChain())) {
				eq("public_chain", rechargeRecord.getPublicChain());
			}
			if (StrUtil.isNotBlank(rechargeRecord.getType())) {
				eq("type", rechargeRecord.getType());
			}
			if (StrUtil.isNotBlank(rechargeRecord.getState())) {
				eq("state", rechargeRecord.getState());
			}
			if (rechargeRecord.getStartTime() != null) {
				ge("create_time", rechargeRecord.getStartTime());
				le("create_time", rechargeRecord.getStartTime().plusDays(1));
			}
			orderByDesc("create_time");
		}};
		Page<RechargeRecord> pageList = rechargeRecordService.page(page, wrapper);
		List<RechargeRecord> records = pageList.getRecords();

		if (CollUtil.isNotEmpty(records)) {
			List<Long> collect = records.stream().map(RechargeRecord::getUserId).collect(Collectors.toList());
			R<List<User>> userList = remoteRippleUserService.getUserList(collect, SecurityConstants.FROM_IN);
			List<User> data = userList.getData();
			records.forEach(record -> {
				data.forEach(item -> {
					if (record.getUserId().equals(item.getUid())) {
						record.setEmail(item.getEmail());
					}
				});
			});
		}
		WalletStatisticsBO<RechargeRecord> bo = new WalletStatisticsBO<>();
		RechargeRecord one = rechargeRecordService.getOne(
				wrapper.select("sum(quantity) 'quantity'")
		);
		bo.setPage(pageList);
		bo.setStatistics(one);
		return R.ok(bo);
	}


	/**
	 * 通过id查询充值记录
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('wallet_rechargerecord_view')")
	public R getById(@PathVariable("id") Long id) {
		return R.ok(rechargeRecordService.getById(id));
	}

	/**
	 * 新增充值记录
	 *
	 * @param rechargeRecord 充值记录
	 * @return R
	 */
	@ApiOperation(value = "新增充值记录", notes = "新增充值记录")
	@SysLog("新增充值记录")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('wallet_rechargerecord_add')")
	public R save(@RequestBody RechargeRecord rechargeRecord) {
		return R.ok(rechargeRecordService.save(rechargeRecord));
	}

	/**
	 * 修改充值记录
	 *
	 * @param rechargeRecord 充值记录
	 * @return R
	 */
	@ApiOperation(value = "修改充值记录", notes = "修改充值记录")
	@SysLog("修改充值记录")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('wallet_rechargerecord_edit')")
	public R updateById(@RequestBody RechargeRecord rechargeRecord) {
		return R.ok(rechargeRecordService.updateById(rechargeRecord));
	}

	/**
	 * 通过id删除充值记录
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除充值记录", notes = "通过id删除充值记录")
	@SysLog("通过id删除充值记录")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('wallet_rechargerecord_del')")
	public R removeById(@PathVariable Long id) {
		return R.ok(rechargeRecordService.removeById(id));
	}


	/**
	 * 导出excel 表格
	 *
	 * @param rechargeRecord 查询条件
	 * @return excel 文件流
	 */
	@ResponseExcel
	@GetMapping("/export")
	@PreAuthorize("@pms.hasPermission('wallet_rechargerecord_export')")
	public List<RechargeRecord> export(RechargeRecord rechargeRecord) {
		return rechargeRecordService.list(Wrappers.query(rechargeRecord));
	}

	/**
	 * app用户充值记录
	 */
	@ApiOperation(value = "app用户充值记录", notes = "app用户充值记录")
	@PostMapping("/app/page")
	public R appPage(@RequestBody MobileRechargeRecord mobileRechargeRecord) {
		Long userId = SecurityUtils.getUser().getId();
		Page appPage = rechargeRecordService.page(mobileRechargeRecord.getPage(), new LambdaQueryWrapper<RechargeRecord>()
				.eq(RechargeRecord::getUserId, userId)
				.eq(StrUtil.isNotBlank(mobileRechargeRecord.getRechargeRecord().getType()), RechargeRecord::getType, mobileRechargeRecord.getRechargeRecord().getType())
				.in(mobileRechargeRecord.getRechargeRecord().getTypeList() != null, RechargeRecord::getType, mobileRechargeRecord.getRechargeRecord().getTypeList())
				.in(StrUtil.equals(mobileRechargeRecord.getRechargeRecord().getState(), WalletStatusEnum.ALL.getStatus()), RechargeRecord::getState,
						WalletStatusEnum.RECHARGING.getStatus(), WalletStatusEnum.RECHARGE_COMPLETED.getStatus(), WalletStatusEnum.RECHARGE_FAILED.getStatus())
				.eq(!StrUtil.equals(mobileRechargeRecord.getRechargeRecord().getState(), WalletStatusEnum.ALL.getStatus()), RechargeRecord::getState, mobileRechargeRecord.getRechargeRecord().getState())
				.ge(mobileRechargeRecord.getRechargeRecord().getStartTime() != null, RechargeRecord::getCreateTime, mobileRechargeRecord.getRechargeRecord().getStartTime())
				.le(mobileRechargeRecord.getRechargeRecord().getEndTime() != null, RechargeRecord::getCreateTime, mobileRechargeRecord.getRechargeRecord().getEndTime())
				.orderByDesc(RechargeRecord::getCreateTime)
		);
		return R.ok(appPage);
	}

	/**
	 * app用户充值记录根据id获取
	 */
	@ApiOperation(value = "app用户充值记录根据id获取", notes = "app用户充值记录根据id获取")
	@GetMapping("/app/{id}")
	public R appPage(@PathVariable("id") Long id) {
		RechargeRecord rechargeRecord = rechargeRecordService.getById(id);
		return R.ok(rechargeRecord);
	}

	/**
	 * web根据用户id获取充值记录列表
	 *
	 * @param id 用户id
	 * @return 提现记录 - 分页
	 */
	@ApiOperation(value = "web根据用户id获取充值记录列表", notes = "web根据用户id获取充值记录列表")
	@GetMapping("/page/user")
	public R<Page<RechargeRecord>> getListByUserId(Page<RechargeRecord> page, Long id) {
		try {
			Page<RechargeRecord> recordPage = rechargeRecordService.page(page, new QueryWrapper<RechargeRecord>() {{
				eq("user_id", id);
				eq("del_flag", "0");
			}});
			return R.ok(recordPage);
		} catch (Exception e) {
			return null;
		}
	}
}
